import store from "@/store/index.js"
import {getUserLocation} from "@/api/map/locate.js"
import {handlePositionError} from "@/utils/errorHandler.js"


class positionTimer{
	constructor(waitSeconds){
		this.timer = null
		this.waitSeconds = waitSeconds
		this.startTimer()
	}
	
	async positionTiming(){
		try{
			const position = await getUserLocation()
			console.log(position)
			const {address} = position
			let legalAddress = true
			if(address.city !== "南京市"){
				legalAddress = false
			}
			store.commit("user/SET_POSITION",{...position,legalAddress})
		}catch(err){
			console.log(err)
			handlePositionError(err)
			this.positionTiming()
		}
	}
	
	
	async startTimer(){
		await this.positionTiming()
		this.timer = await setTimeout(async () => {
			// 业务方法
			await this.positionTiming()
			// 重调timer
			this.startTimer()
		},this.waitSeconds*1000)
	}
	
	clearTravelTimer(){
		 this.timer && clearTimeout(this.timer)
	}
	
}




export const registerPositionTimer = async () => {
	// let waitSeconds = 1000*60*3 // 每隔3min刷新一次定位
	let waitSeconds = 1000*10 // 测试：隔10s刷新一次定位
	new positionTimer(waitSeconds)
	
}